package org.elec.mac.inter;

import org.elec.mac.entity.SAdvert;
import org.elec.mac.exception.ErrorCode;
import org.elec.mac.exception.ErrorMsg;
import org.elec.mac.service.SAdvertService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/adv")
public class IntAdvertisementController {

    @Value("${annex.image.url}")
    private String imageurl;

    @Autowired
    private SAdvertService advertService;

    @RequestMapping("/getadvert.do")
    public void getAdvertisement(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<String> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        int code = ErrorCode.SUCCESS;
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("state", 1);
            List<SAdvert> adverts = advertService.list(params);
            for (SAdvert item:adverts) {
                if(item.getType() == 0) {
                    list1.add(imageurl+item.getPath());
                } else if (item.getType() == 1) {
                    list2.add(imageurl+item.getPath());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取广告图接口出错");
            code = ErrorCode.ERR_FAILED;
        }
        JSONObject advertList = new JSONObject();
        advertList.put("type1", list1);
        advertList.put("type2", list2);
        JSONObject body = new JSONObject();
        body.put("advertList", advertList);
        JSONObject result = new JSONObject();
        result.put("code", code);
        result.put("msg", ErrorMsg.errorMessage(code));
        result.put("body", body);
        response.setContentType("text/json");
        response.setCharacterEncoding("UTF-8");
        log.info(result.toString());
        response.getWriter().write(result.toString());
    }

}
